﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace STAR.Spring.Framework.Module
{
    public class CustomResponseFactory
    {
        public static ICustomResponse  GetCustomResponse(string name)
        {
            string typeName = GetTypeByName(name);
            if (string.IsNullOrEmpty(typeName))
            {
                throw new Exception(string.Format("自定义配置不正确：{0}没有配置", typeName));
            }

            Object instance = null;
            try
            {
                Type instanceType = Type.GetType(typeName);
                instance = Activator.CreateInstance(instanceType);
            }
            catch
            {
                throw new Exception(string.Format("自定义配置不正确：{0}创建失败", typeName));
            }
            if (!(instance is ICustomResponse))
            {
                throw new Exception(string.Format("自定义配置不正确：{0}没有实现ICustomResponse", typeName));
            }
            return (ICustomResponse)instance;
        }

        /// <summary>
        /// 或者配置文件中类型名称
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private static string GetTypeByName(string name)
        {
            Config.ConfigInfo info = Cache.CacheHelper.GetConfigInfo();
            if (info.IsAnaysleOk)
            {
                if (info.CustomResponseInfos.Keys.Contains(name))
                {
                    return info.CustomResponseInfos[name];
                }
                else
                {
                    throw new Exception(string.Format("自定义配置不正确：{0}没有配置", name));
                }
            }
            else
            {
                throw new Exception("配置文件解析错误",info.AnaysleException);
            }

        }
    }
}
